import 'package:chat_shop/common/const/cosnt.dart';
import 'package:chat_shop/login&regist/view/input_pwd_view.dart';
import 'package:chat_shop/login&regist/view/login_view.dart';
import 'package:chat_shop/login&regist/view/regist_login_email.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../common/widget/bottom_btn.dart';
import 'forget_pwd_view.dart';

class AlertLoginView extends StatefulWidget {
  /// 0 手机登录 1 邮箱登录 2 注册
  final int status;
  final String title;
  final bool isforget;
  const AlertLoginView({Key? key, this.status = 0, this.title = "登录", this.isforget = false}) : super(key: key);

  @override
  _AlertLoginViewState createState() => _AlertLoginViewState();
}

class _AlertLoginViewState extends State<AlertLoginView> {
  int step = 0;
  bool isemail = false;
  String phonecode = "";
  TextEditingController _controller = TextEditingController();
  FocusNode _focusNode = FocusNode();
  TextEditingController _controller1 = TextEditingController();
  FocusNode _focusNode1 = FocusNode();

  /// 忘记密码
  bool isforget = false;
  @override
  void initState() {
    super.initState();
    isemail = widget.status == 1;
    if (widget.isforget) {
      step = 1;
      isforget = true;
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _controller1.dispose();
    super.dispose();
  }

  void _resend() async {
    EasyLoading.show(status: "Loading...");
    await Future.delayed(const Duration(seconds: 1));
    EasyLoading.dismiss();
    // 回传新发的验证码
    setState(() {
      step = 1;
    });
  }

  void _login() async {
    EasyLoading.show(status: "Loading...");
    await Future.delayed(const Duration(seconds: 1));
    EasyLoading.dismiss();
    SharedPreferences.getInstance().then((value) => value.setString(AppConst.KEY_user_token, "token"));
    _userinfo();
  }

  void _loginEmail() async {
    if (_controller1.text.isEmpty) {
      EasyLoading.showToast("请输入密码");
      return;
    }
    EasyLoading.show(status: "Loading...");
    await Future.delayed(const Duration(seconds: 1));
    EasyLoading.dismiss();
    SharedPreferences.getInstance().then((value) => value.setString(AppConst.KEY_user_token, "token"));
    _userinfo();
  }

  void _userinfo() async {
    EasyLoading.show(status: "Loading...");
    await Future.delayed(const Duration(seconds: 1));
    EasyLoading.dismiss();
    Navigator.of(context).pushReplacementNamed('/root');
  }

  Widget _create() {
    switch (widget.status) {
      case 1:
      case 0:
        {
          if (step == 1) {
            // 第二部
            return _createNextWidget();
          }
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                Row(
                  children: [
                    _Item(
                      titles: "手机",
                      onTap: () {
                        setState(() {
                          isemail = false;
                        });
                        _controller.clear();
                      },
                      isselect: !isemail,
                    ),
                    _Item(
                      titles: "邮箱",
                      onTap: () {
                        setState(() {
                          isemail = true;
                        });
                        _controller.clear();
                      },
                      isselect: isemail,
                    )
                  ],
                ),
                SizedBox(
                  height: 15,
                ),
                TextField(
                  inputFormatters: isemail ? [] : [FilteringTextInputFormatter.digitsOnly],
                  keyboardType: isemail ? TextInputType.emailAddress : TextInputType.number,
                  controller: _controller,
                  focusNode: _focusNode,
                  maxLength: isemail ? null : 11,
                  decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: AppColor.mainColor, width: 1.0),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: AppColor.fontgrey, width: 1.0),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 10),
                      counterText: ""),
                ),
                BottomButton(
                  title: '下一步',
                  margin: const EdgeInsets.only(top: 20),
                  onTap: () {
                    if (_controller.text.isEmpty) {
                      EasyLoading.showToast(isemail ? "请输入邮箱号" : "请输入手机号码");
                      return;
                    }
                    if (isemail) {
                      setState(() {
                        step = 1;
                      });
                    } else {
                      _resend();
                    }
                  },
                ),
                SizedBox(
                  height: 50,
                )
              ],
            ),
          );
        }
        break;
      case 2:
        {
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                Row(
                  children: [
                    _Item(
                      titles: "手机",
                      onTap: () {
                        setState(() {
                          isemail = false;
                        });
                        _controller.clear();
                      },
                      isselect: !isemail,
                    ),
                    _Item(
                      titles: "邮箱",
                      onTap: () {
                        setState(() {
                          isemail = true;
                        });
                        _controller.clear();
                      },
                      isselect: isemail,
                    )
                  ],
                ),
                SizedBox(
                  height: 15,
                ),
                _createRegister(),
                SizedBox(
                  height: 50,
                )
              ],
            ),
          );
        }
        break;
      default:
        return SizedBox();
    }
  }

  Widget _createNextWidget() {
    if (isforget == true) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    _Item(
                      titles: "手机",
                      onTap: () {
                        setState(() {
                          isemail = false;
                        });
                        _controller.clear();
                      },
                      isselect: !isemail,
                    ),
                    _Item(
                      titles: "邮箱",
                      onTap: () {
                        setState(() {
                          isemail = true;
                        });
                        _controller.clear();
                      },
                      isselect: isemail,
                    )
                  ],
                ),
                SizedBox(
                  height: 15,
                ),
                ForgetPwdView(
                  isemail: isemail,
                  onCancel: () {
                    if (widget.isforget) {
                      // 设置登录密码,的时候忘记免密就返回
                      Navigator.pop(context);
                      return;
                    }
                    setState(() {
                      isforget = false;
                    });
                  },
                ),
              ],
            ),
          ),
          Divider(
            height: 30,
          ),
          InkWell(
              onTap: () {
                if (widget.isforget) {
                  // 设置登录密码,的时候忘记免密就返回
                  Navigator.pop(context);
                  return;
                }
                setState(() {
                  isforget = false;
                });
              },
              child: Padding(
                padding: const EdgeInsets.only(left: 20.0),
                child: Image.asset("assets/yanzhengma_fanhui.png"),
              )),
          SizedBox(
            height: 20,
          )
        ],
      );
    }
    if (isemail) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                Row(
                  children: [
                    _Item(
                      titles: "手机",
                      isselect: !isemail,
                    ),
                    _Item(
                      titles: "邮箱",
                      isselect: isemail,
                    ),
                    Spacer(),
                    InkWell(
                        onTap: () {
                          setState(() {
                            isforget = true;
                          });
                        },
                        child: Text(
                          "忘记密码?",
                          style: AppFont.textStyle(15),
                        )),
                  ],
                ),
                SizedBox(
                  height: 15,
                ),
                TextField(
                  controller: _controller1,
                  focusNode: _focusNode1,
                  obscureText: true,
                  decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: AppColor.mainColor, width: 1.0),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: AppColor.fontgrey, width: 1.0),
                      ),
                      contentPadding: const EdgeInsets.symmetric(horizontal: 10)),
                ),
                BottomButton(
                  title: '登录',
                  margin: const EdgeInsets.only(top: 20),
                  onTap: _loginEmail,
                ),
              ],
            ),
          ),
          Divider(
            height: 30,
          ),
          InkWell(
              onTap: () {
                setState(() {
                  step = 0;
                });
              },
              child: Padding(
                padding: const EdgeInsets.only(left: 20.0),
                child: Image.asset("assets/yanzhengma_fanhui.png"),
              )),
          SizedBox(
            height: 50,
          )
        ],
      );
    } else {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                Row(
                  children: [
                    _Item(
                      titles: "手机",
                      isselect: !isemail,
                    ),
                    _Item(
                      titles: "邮箱",
                      isselect: isemail,
                    ),
                    Spacer(),
                    Text(
                      "未收到验证码?",
                      style: AppFont.textStyle(15),
                    ),
                  ],
                ),
                SizedBox(
                  height: 15,
                ),
                InputPwdView(
                  onChanged: (sender) {
                    phonecode = sender;
                  },
                ),
                BottomButton(
                  title: '登录',
                  margin: const EdgeInsets.only(top: 20),
                  onTap: _login,
                ),
              ],
            ),
          ),
          Divider(
            height: 30,
          ),
          InkWell(
            onTap: () {
              setState(() {
                step = 0;
              });
            },
            child: Padding(
              padding: const EdgeInsets.only(left: 20.0),
              child: Icon(
                Icons.arrow_back,
                color: Colors.black,
                size: 16,
              ),
            ),
          ),
          SizedBox(
            height: 50,
          )
        ],
      );
    }
  }

  Widget _createRegister() {
    if (isemail) {
      return RegistEmailView();
    } else {
      return RegistLoginView();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration:
          BoxDecoration(color: AppColor.mainColor, borderRadius: BorderRadius.vertical(top: Radius.circular(10))),
      padding: EdgeInsets.only(top: 10),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            height: 6,
            width: 50,
            margin: const EdgeInsets.only(bottom: 10),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.5),
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 17.0),
            child: Text(
              isforget ? "重置登录密码" : widget.title,
              style: AppFont.textStyle(18, color: Colors.white),
            ),
          ),
          Container(
              padding: EdgeInsets.only(
                  top: 30, bottom: MediaQuery.of(context).padding.bottom + MediaQuery.of(context).viewInsets.bottom),
              decoration:
                  BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(8))),
              child: _create()),
        ],
      ),
    );
  }
}

class _Item extends StatelessWidget {
  final bool isselect;
  final String titles;
  final Function()? onTap;

  const _Item({Key? key, this.isselect = false, required this.titles, this.onTap}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.only(right: 20),
        child: Text(
          titles,
          style: AppFont.textStyle(18, color: !isselect ? AppColor.fontgrey : AppColor.mainColor),
        ),
      ),
    );
  }
}
